import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import Icon from '@ant-design/icons';
import { TabC } from '../../../../comps';
import HistoryPriceC from './historyPriceC';
import BaseInfoC from './baseInfo';
import PlanInfoC from './planInfo';
import RelatedPositionC from './relatedPosition';
import CardC from '../../Barra/comps/cardC';
import style from './index.less';
import nodata from '../../../../assets/busi/workStation/Barra/nodata.png';
import bg from '../../../../assets/busi/workStation/Nonstandard/info_bg.png';
import moment from 'moment';
@connect(({ loading, informationM, relatedPositionM }) => ({
  loading,
  informationM,
  relatedPositionM,
}))
export default class NonStardardInfoC extends PureComponent {
  state = {
    activeKey: 'baseInfo',
    securityType: undefined,
    securityCode: undefined,
    statusLength: 0, // 续存个数
  };
  componentDidMount() {
    this.props.onRef(this);
    this.setState({
      status: ['11', '12', '13', '14', '1', '3'].includes(this.props.state) ? false : true,
    });
    this.getBaseInfo(this.props.record);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.state != this.props.state) {
      this.setState({
        status: ['11', '12', '13', '14', '1', '3'].includes(nextProps.state) ? false : true,
      });
    }
    if (JSON.stringify(nextProps.record) != JSON.stringify(this.props.record)) {
      this.getBaseInfo(nextProps.record);
    }
  }

  // 获取理财直融/非理财直融数据
  getBaseInfo = (record) => {
    this.setState(
      {
        securityType: record?.assetTypeFB,
        securityCode: record?.stockCode ? record?.stockCode.split('.')[0] : undefined,
      },
      () => {
        const { securityCode, securityType } = this.state;
        if (securityType == '12') {
          // 非理财直融
          this.props.dispatch({
            type: 'informationM/getDataById',
            payload: {
              tradingcode: securityCode,
              // id: '6798696df13d4a5b825629598c22ea57'
            },
          });
        } else if (securityType == '7') {
          // 理财直融
          this.props.dispatch({
            type: 'informationM/editInformationById',
            payload: {
              // id: '288bc5ad721b9d5c01727eb76d5d5b15'
              tradingcode: securityCode,
              exchangecode: record?.exchangeCode,
            },
          });
        }
        this.props.dispatch({
          type: 'relatedPositionM/getTableDate',
          payload: {
            securitiesCode: record.stockCode?.split('.')[0],
            product: this.props.gzCode,
            assetType: record.assetTypeFB,
            exchangeCode: record.exchangeCode,
          },
          callback: (res) => {
            if (res) {
              let length = 0;
              res.map((item) => {
                if (item.amount) length++;
              });
              this.setState({
                statusLength: length, // 表格头
              });
            } else {
              this.setState({
                statusLength: 0,
              });
            }
          },
        });
      },
    );
  };

  // 展开收起
  stateOnChange = () => {
    this.setState(
      {
        status: this.state.status == 1 ? false : true,
      },
      () => {
        this.props.stateOnChange(this.state.status ? 1 : 2);
      },
    );
  };

  // tab切换
  tabOnclick = (activeKey) => {
    this.setState({ activeKey });
  };

  // 刷新历史定价结果数据
  refreshPrice = () => {
    this.HistoryPrice?.refresh();
  };

  render() {
    const { status, activeKey, securityType, securityCode, statusLength } = this.state;
    const {
      productCode,
      record,
      rootId,
      gzCode,
      informationM: { formDatas, basicInfo },
      state,
      modes,
    } = this.props;
    let nextData;
    let stockName = '';
    if (securityType == '12') {
      formDatas.zgtzptNonstandarCashFlows.length &&
        formDatas.zgtzptNonstandarCashFlows.map((item, index) => {
          let nowDate = moment().format('YYYY-MM-DD');
          if (moment(item?.startDate).format('YYYY-MM-DD') <= nowDate && moment(item?.endDate).format('YYYY-MM-DD') >= nowDate) {
            if (formDatas.zgtzptNonstandarCashFlows.length > index) {
              nextData = moment(formDatas.zgtzptNonstandarCashFlows[index + 1]?.startDate).format('YYYY-MM-DD');
            }
          }
        });
      stockName = formDatas.baseInfo.tradingname;
    } else {
      basicInfo?.zgtzptNonstandarCashFlows &&
        basicInfo?.zgtzptNonstandarCashFlows.length &&
        basicInfo?.zgtzptNonstandarCashFlows.map((item, index) => {
          let nowDate = moment().format('YYYY-MM-DD');
          if (moment(item?.startDate).format('YYYY-MM-DD') <= nowDate && moment(item?.endDate).format('YYYY-MM-DD') >= nowDate) {
            if (basicInfo.zgtzptNonstandarCashFlows.length > index) {
              nextData = moment(basicInfo.zgtzptNonstandarCashFlows[index + 1]?.startDate).format('YYYY-MM-DD');
            }
          }
        });
      stockName = basicInfo.chiname;
    }
    return (
      <div className={style.mainBox}>
        <div className={style.openBox} style={{ display: status ? 'block' : 'none' }}>
          {/* 展开 */}
          <CardC
            title='非标信息'
            type='14'
            showContent={status}
            onExpendClick={this.stateOnChange}
            titleTip={securityCode ? `非标(${securityType == '7' ? '' : '非'}理财直融)-${securityCode || ''}-${stockName || ''}` : ''}
            content={
              <div className={style.boxContent}>
                {securityCode ? (
                  <TabC
                    type='secondTab'
                    tabSource={
                      modes == 'BOOKKEEPING_MODE' || modes == 'COMMAND_MODE'
                        ? [
                            {
                              title: '基本信息',
                              key: 'baseInfo',
                              content: <BaseInfoC securityType={securityType} securityTypeChange={this.props.securityTypeChange} changePage={this.props.changePage} />,
                            },
                            { title: '还本付息计划', key: 'plan', content: <PlanInfoC securityType={securityType} /> },
                            {
                              title: '历史定价结果',
                              key: 'history',
                              content: (
                                <HistoryPriceC
                                  // searchData={{productCode:this.props.productCode,securityCode:this.props.securityCode}}
                                  searchData={{ productCode: productCode, securityCode: securityCode }}
                                  changePage={this.props.changePage}
                                  onRef={(ref) => {
                                    this.HistoryPrice = ref;
                                  }}
                                />
                              ),
                            },
                            { title: '关联持仓', key: 'position', content: <RelatedPositionC record={record} rootId={rootId} gzCode={gzCode} /> },
                          ]
                        : [{ title: '关联持仓', key: 'position', content: <RelatedPositionC record={record} rootId={rootId} gzCode={gzCode} /> }]
                    }
                    activeKey={modes == 'BOOKKEEPING_MODE' || modes == 'COMMAND_MODE' ? activeKey : 'position'}
                    onChange={this.tabOnclick}
                  />
                ) : (
                  <div className={style.nodata}>
                    <Icon component={() => <img src={nodata} alt='icon' style={{ marginBottom: '60px', width: '378px', height: '152px' }} />} />
                    <div>请您切换至有非标持仓的产品</div>
                  </div>
                )}
              </div>
            }
          />
        </div>
        <div className={style.closeBox} style={{ display: status ? 'none' : 'block', overflow: 'hidden' }}>
          {/* 收起 */}
          <CardC
            title='非标信息'
            type='14'
            showContent={status}
            onExpendClick={this.stateOnChange}
            content={
              <div>
                {securityCode ? (
                  <div>
                    {(state == 11 || state == 12) && (
                      <div className={style.content}>
                        <div>
                          当前非标资产为<span className={style.name}>{securityCode ? securityCode + '-' + stockName : '--'}</span>
                        </div>
                        <div>
                          下一付息日为
                          <br />
                          <span className={style.name}>{nextData || '--'}</span>
                        </div>
                        <div>
                          在<span className={style.num}>{statusLength}</span>只产品中有存续持仓
                        </div>
                      </div>
                    )}
                    {(state == 1 || state == 3 || state == 13 || state == 14) && (
                      <div className={style.content}>
                        <div>
                          当前非标资产为<span className={style.num}>{securityCode ? securityCode + '-' + stockName : '--'}</span>
                        </div>
                        <div>
                          下一付息日为<span className={style.num}>{nextData || '--'}</span>，在 <span className={style.num}>{statusLength}</span> 只产品中有存续持仓
                        </div>
                      </div>
                    )}
                    <div className={style.closeContbg}>
                      <img src={bg} />
                    </div>
                  </div>
                ) : (
                  <div className={style.content}>
                    请您切换至有非标持仓的产品
                    <div className={style.closeContbg}>
                      <img src={bg} />
                    </div>
                  </div>
                )}
              </div>
            }
          />
        </div>
      </div>
    );
  }
}

// props默认值
NonStardardInfoC.propsTypes = {
  securityTypeChange: PropTypes.func, // 改变标的类型
  changePage: PropTypes.func, // 改变是否显示主页面
  record: PropTypes.object, // assetTypeFB--标的类型：7-非标(理财直融) 12- 非标(非理财直融)stockCode--标的code
  productCode: PropTypes.string, // 产品code（产品code不影响非标信息的展示，只是记录在内存中，用于判断在点击关联持仓中的产品时，是否有其他模块的产品保持一致，若一致，则不抛出事件，若不一致，则抛出事件）
};
